package com.ruoyi.durian.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.DurianConstant;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.DurianRedisKeysType;
import com.ruoyi.common.enums.OrderType;
import com.ruoyi.common.utils.RedisGeoUtils;
import com.ruoyi.common.utils.rabbitmq.RabbitSendUtils;
import com.ruoyi.durian.domain.LlCardPackage;
import com.ruoyi.durian.domain.LlCoupon;
import com.ruoyi.durian.domain.LlOrder;
import com.ruoyi.durian.domain.LlOrderInfo;
import com.ruoyi.durian.mapper.LlCardPackageMapper;
import com.ruoyi.durian.mapper.LlCouponMapper;
import com.ruoyi.durian.mapper.LlOrderInfoMapper;
import com.ruoyi.durian.service.LlOrderService;
import com.ruoyi.durian.mapper.LlOrderMapper;
import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author lenovo
 * @description 针对表【ll_order(订单模块-订单表)】的数据库操作Service实现
 * @createDate 2024-07-29 21:04:10
 */
@Service
public class LlOrderServiceImpl extends ServiceImpl<LlOrderMapper, LlOrder>
        implements LlOrderService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private RedisGeoUtils redisGeoUtils;

    @Resource
    private LlOrderMapper llOrderMapper;

    @Resource
    private LlOrderInfoMapper llOrderInfoMapper;

    @Resource
    private RedissonClient redissonClient;

    @Resource
    private RabbitSendUtils rabbitSendUtils;

    @Resource
    private LlCardPackageMapper llCardPackageMapper;

    @Resource
    private LlCouponMapper llcouponMapper;

    /**
     * 乘客取消订单
     *
     * @param orderId 订单id
     * @return
     */
    @Override
    @Transactional
    public AjaxResult closeOrder(Integer orderId) {

        Integer userId = 1204;

        RLock redLock = redissonClient.getLock(DurianConstant.START_ORDER_KEY);
        RedissonMultiLock lock = new RedissonMultiLock(redLock);
        lock.lock();
        try {
            // 获取订单在订单地图中的key
            String orderString = stringRedisTemplate.opsForValue().get(DurianRedisKeysType.ORDER.getKey() + userId);
            LlOrder order = JSONObject.parseObject(orderString, LlOrder.class);
            if (order.getStatus() < OrderType.WAITING_AFTER.getCode()){
                return AjaxResult.error("司机已到达指定地点无法取消订单");
            }
            // 删除redis中的订单
            stringRedisTemplate.delete(DurianRedisKeysType.ORDER.getKey() + userId);
            // 删除订单在地图中的位置
            redisGeoUtils.geoDel(DurianRedisKeysType.PERSON.getKey() + userId, orderString);

            LlOrder llOrder = llOrderMapper.selectById(orderId);
            LambdaQueryWrapper<LlOrderInfo> qw = new LambdaQueryWrapper<>();
            qw.eq(LlOrderInfo::getOrderId, orderId);
            LlOrderInfo orderInfo = llOrderInfoMapper.selectOne(qw);

            llOrder.setStatus(OrderType.DELETE_ORDER.getCode());
            orderInfo.setStatus(OrderType.DELETE_ORDER.getCode());

            llOrderMapper.updateById(llOrder);
            llOrderInfoMapper.updateById(orderInfo);

            rabbitSendUtils.sendMessage(orderInfo.getDriverId(), "乘客取消订单。。。。");
            rabbitSendUtils.sendMessage(userId, "取消订单成功！！！！");
        } finally {
            lock.unlock();
        }

        return AjaxResult.success("取消成功");
    }

    /**
     * 结算使用优惠券
     * @param orderId
     * @param couponId
     * @return
     */
    @Override
    public AjaxResult useCoupon(Integer orderId, Integer couponId) {
        Integer userId=619;

        if (couponId == null || orderId==null){
            return AjaxResult.error("订单不存在，或者优惠券已使用");
        }

        //按照订单id查询订单
        LlOrder llOrder = llOrderMapper.selectById(orderId);
        //获取原本的订单价格
        BigDecimal price = llOrder.getPrice();
        //按照卡包的优惠券id查询卡包
        LlCardPackage cardPackage = llCardPackageMapper.selectById(couponId);
        if (llOrder==null || cardPackage==null){
            return AjaxResult.error("订单不存在，或者优惠券已使用");
        }
        //根据卡包里面对应的优惠券id进入优惠券表查询优惠券具体的信息
        LlCoupon llCoupon = llcouponMapper.selectById(cardPackage.getCouponId());

        //优惠券状态   1 打折  2 满减
        if (llCoupon.getType()==1){
            //获取折扣
            BigDecimal discount = BigDecimal.valueOf(llCoupon.getSale());
            //计算折扣后的价格
            BigDecimal discountPrice = price.multiply(discount.divide(BigDecimal.valueOf(10)));
            //优惠的金额
            BigDecimal subtract = price.subtract(discountPrice);
            if (subtract.compareTo(llCoupon.getSaleMoney())>=0){
                llOrder.setPrice(llCoupon.getSaleMoney());
            }
            //将订单价格修改为折扣后的价格
            llOrder.setPrice(discountPrice);
        }else{

            //获取满减
            BigDecimal discount = BigDecimal.valueOf(llCoupon.getSale());
            if (price.compareTo(BigDecimal.valueOf(llCoupon.getMax()))>=0){
                //计算满减后的价格
                BigDecimal discountPrice = price.subtract(discount);
                //将订单价格修改为满减后的价格
                llOrder.setPrice(discountPrice);
            }else{
                return AjaxResult.error("不满足满减条件");
            }
        }

        return AjaxResult.success("优惠券使用成功");
    }
}




